package cn.com.dstz.taglib;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;

import cn.com.dstz.utils.Common;

public class ConfigTaglib extends TagSupport{
	
	@Override
	public int doEndTag( ) throws JspException {
		return EVAL_PAGE;
	}

	@Override
	public int doStartTag( ) throws JspException {
		
		JspWriter out = this.pageContext.getOut( );
		try{
			out.print( getCheckbox( ) );
		}catch( IOException e ){
			e.printStackTrace();
		}
		
		return SKIP_BODY;
	}
	
	private String getCheckbox( ){
		StringBuffer buffer = new StringBuffer( );
		
		if( groupList == null || groupList.size( ) == 0 ){
			return "系统繁忙，无法获取分组信息";
		}
		
		boolean hasConfig = true;
		
		// 表示没有配置，只是查询自己的
		if( StringUtils.isBlank( config ) ){
			hasConfig = false;
		}
		
		for( Map< String, Object > group : groupList ){
			String name = Common.convert( group.get( "name" ) );
			String checked = "";
			
			if( hasConfig ){
				String [] groupIds = StringUtils.split( config, "," );
				
				for( String id : groupIds ){
					if( id.equals( group.get( "id" ).toString( ) )){
						checked = "checked";
					}
				}
			}
			
			String checkbox = "<input type=\"checkbox\" name=\"" + domname + "\" value=\"" + group.get( "id" ) + "\" " + checked + "/>";
			
			buffer.append( checkbox );
			buffer.append( name );
		}
		
		return buffer.toString( );
		
	}
	
	

	@Override
	public void release( ) {
		super.release( );
		domname = null;
		config = null;
		groupList = null;
	}
	
	private List< Map< String, Object >> groupList;
	private String config;
	private Integer groupid;
	private String domname;	

	public String getDomname( ) {
		return domname;
	}

	public void setDomname( String domname ) {
		this.domname = domname;
	}
	

	public List< Map< String, Object >> getGroupList( ) {
		return groupList;
	}

	public String getConfig( ) {
		return config;
	}

	public void setConfig( String config ) {
		this.config = config;
	}

	public void setGroupList( List< Map< String, Object >> groupList ) {
		this.groupList = groupList;
	}

	public Integer getGroupid( ) {
		return groupid;
	}

	public void setGroupid( Integer groupid ) {
		this.groupid = groupid;
	}

	private static final long serialVersionUID = 1L;

}
